const app = getApp();
const db = wx.cloud.database().collection("cars");
const chooseLocation = requirePlugin('chooseLocation');
Page({
  data: { 
    value: '',
    equipmentList: [] ,// 初始化一个空数组用于存储从数据库获取的设备信息
    enable: false,
    actionText: '',
    loadingProps: {
      size: '50rpx',
    },
    isEditing: false,
    editId: null,
    cname: '',
    business: '',
    contact: '',
    cars: '',
    location: '',
    imgUrl:'',
    address: "",
    locationName: "",
    latitude:"",//维度
    longitude:"",//经度
    tempImgUrl: '', // 用于保存暂存图片路径

    cars: [
      { label: '五座小车', value: '五座小车' },
      { label: '七座商务车', value: '七座商务车' },
      { label: '货车', value: '货车' },
      { label: '发电车', value: '发电车' },
      { label: '洒水车', value: '洒水车' },
      { label: '其他', value: '其他' },
    ],
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
    newModuleIndex: 0, // 新模块的索引，用于唯一标识每个新添加的模块
    cityVisible: false, // 城市选择器是否可见
    cityValue: [], // 城市选择器的值
    filmSBZPList: [], // 租赁设备列表
    ename: '', // 设备名称
    tempImgUrl: '' // 用于保存暂存图片路径
  },
  onLoad: function() {
    this.getEquipmentData(); // 在页面加载时调用获取设备信息的函数
  },
  handleDelete2(e) {
    const { id } = e.currentTarget.dataset; // 获取当前模块的 moduleId
    const { filmSBZPList } = this.data; // 获取当前设备列表
  
    // 找到对应 moduleId 的模块索引
    const moduleIndex = filmSBZPList.findIndex(item => item.moduleId === id);
  
    if (moduleIndex !== -1) {
      // 移除对应索引的模块
      filmSBZPList.splice(moduleIndex, 1);
  
      // 更新设备列表数据
      this.setData({
        filmSBZPList
      });
    } else {
      console.error('Module not found');
    }
  },

  viewDetail(e) {
   
    const index = e.currentTarget.dataset.index; // 获取点击的<c-filmcard>的索引
    console.log(index)
    const selectedItem = this.data.equipmentList[index]; // 获取对应索引的设备信息
    
    // 检查selectedItem是否为undefined或null
    if (!selectedItem) {
      console.error("Selected item is undefined or null");
      return;
    }
    
    console.log(selectedItem._id)
    // 跳转到详细信息页面，并传递选定的设备信息
    wx.navigateTo({
      url: '/pages/film-CLZP-detail/film-CLZP-detail?id=' + selectedItem._id
    });
  },
  // 获取设备信息的函数
  getEquipmentData: function() {
    // 从 Cloud 数据库中获取 equipment 表中的数据
    db.where({
      _openid: app.globalData.user_openid,
      
    }).get().then(res => {
      console.log(res.data); // 确保获取到数据
  
      this.setData({
        equipmentList: res.data // 将获取的数据设置到页面的数据属性中
      });
    }).catch(err => {
      console.error(err);
    });
  },
  ready() {
    this.setData({ enable: true });
    setTimeout(() => {
      this.setData({ enable: false });
    }, 1000);
  },
  onRefresh() {
    this.setData({ enable: true });
    this.getEquipmentData();
    setTimeout(() => {
      this.setData({ enable: false });
    }, 1500); 
  }
  ,
  onScroll(e) {
    const { scrollTop } = e.detail;
    this.setData({ scrollTop });
  },
 
  handleDelete(e) {
    const index = e.currentTarget.dataset.index;
    const item = this.data.equipmentList[index];
    const id = item._id;
    
    db.doc(id).remove()
      .then(() => {
        wx.showToast({ title: '删除成功', icon: 'none' });
        this.getEquipmentData();
      })
      .catch(err => {
        wx.showToast({ title: '删除失败', icon: 'none' });
        console.error('Failed to delete item:', err);
      });
  },

  //地图相关
  onShow() {
    const location = chooseLocation.getLocation();
    if (location) {
      this.setData({
        address: location.address || "",
        locationName: location.name || "",
        location: location.address || "",
        latitude: location.latitude || "",
        longitude: location.longitude || ""
      });
    }
  },

  showMap() {
    // 调用选择位置插件
    wx.chooseLocation({
      success: (location) => {
        const marker = {
          id: 1,
          latitude: location.latitude,
          longitude: location.longitude,
          title: '新地点',
        };
        const markers = [marker];
  
        // 更新地图标记点
        this.setData({
          markers,
          scale: 16,
          address: location.address ,
          locationName: location.name ,
          location: location.address ,
          latitude: location.latitude ,
          longitude: location.longitude 
        });
  
        // 刷新页面以获取最新的数据
        this.getEquipmentData();
      },
      fail: (err) => {
        console.error('选择位置失败', err);
      }
    });
  },

  handleEdit(e) {
    const index = e.currentTarget.dataset.index;
    const item = this.data.equipmentList[index];
    const location = item.location2; // 获取设备的地理位置信息
  
    // 创建地图上下文
    this.mapCtx = wx.createMapContext("myMap");
  
    // 创建标记点
    const marker = {
      id: 1,
      latitude: location[1],
      longitude: location[0],
      title: item.cname,
    };
    const markers = [marker];
  
  
    // 更新页面数据，包括已有的图片和其他信息
    this.setData({
      isEditing: true,
      editId: item._id,
      cname: item.cname,
      business: item.business,
      contact: item.contact,
      imgUrl: item.logo_url,  // Current image
      oldImgUrl: item.logo_url,  // Save old image
      location: item.location,

      filmSBZPList: item.cars,
      markers,
      scale: 16, // Set zoom level
    });
  },
   
  // 输入设备名称
  onInputEname(e) {
    const { id } = e.currentTarget.dataset;
    const { value } = e.detail;
    const { filmSBZPList } = this.data;
  
    // 找到对应 moduleId 的模块索引
    const moduleIndex = filmSBZPList.findIndex(item => item.moduleId === id);
  
    if (moduleIndex !== -1) {
      // 设置当前模块的 ename
      filmSBZPList[moduleIndex].ename = value;
      this.setData({ filmSBZPList });
    } else {
      console.error('Module not found');
    }
  },
  // 输入借用单价
  onInputPrice(e) {
    const { id } = e.currentTarget.dataset;
    const { value } = e.detail;
    const { filmSBZPList } = this.data;
  
    // 找到对应 moduleId 的模块索引
    const moduleIndex = filmSBZPList.findIndex(item => item.moduleId === id);
  
    if (moduleIndex !== -1) {
      // 设置当前模块的价格
      filmSBZPList[moduleIndex].price = value;
      this.setData({ filmSBZPList });
    } else {
      console.error('Module not found');
    }
  },
  
  onInputRemark(e) {
    const { id } = e.currentTarget.dataset;
    const { value } = e.detail;
    const { filmSBZPList } = this.data;
  
    // 找到对应 moduleId 的模块索引
    const moduleIndex = filmSBZPList.findIndex(item => item.moduleId === id);
  
    if (moduleIndex !== -1) {
      // 设置当前模块的备注
      filmSBZPList[moduleIndex].remark = value;
      this.setData({ filmSBZPList });
    } else {
      console.error('Module not found');
    }
  },
  
  addFilmSBZP() {
    const { filmSBZPList } = this.data;
  let newModuleIndex = 1; // 设置默认的新模块索引为 1

  if (filmSBZPList.length > 0) {
    // 获取最后一个元素的 moduleId
    const lastModuleId = filmSBZPList[filmSBZPList.length - 1].moduleId;
    // 从 moduleId 中提取数字部分
    const lastModuleIndex = parseInt(lastModuleId.replace("e", ""));
    // 新模块索引为最后一个 moduleId 的数字部分加 1
    newModuleIndex = lastModuleIndex + 1;
  }
    const newFilmSBZP = {
      ename: '',
      price: '',
      remark: '',
      originFiles: [],
      cityText: '',
      moduleId: `e${newModuleIndex}`, // 设置模块的 ID
      priceError: false // 添加 priceError 字段用于记录价格输入是否异常
    };
  
    filmSBZPList.push({ ...newFilmSBZP });
    
    this.setData({
      filmSBZPList,
      newModuleIndex,
    });
  },

  
  // 在 handleSuccess 方法中获取 moduleId 并设置图片信息
  handleSuccess(e) {
    const moduleId = e.currentTarget.dataset.id;
    const { files } = e.detail;
    const { filmSBZPList } = this.data;

    const moduleIndex = filmSBZPList.findIndex(item => item.moduleId === moduleId);

    if (moduleIndex !== -1) {
      filmSBZPList[moduleIndex].picurl = files.map(file => ({ url: file.url }));
      this.setData({ filmSBZPList });
    } else {
      console.error('Module not found');
    }
  },
  
  handleRemove(e) { 
    console.log('handleRemove called'); 
    const moduleId = e.currentTarget.dataset.id; 
    const { filmSBZPList } = this.data; 

    const moduleIndex = filmSBZPList.findIndex(item => item.moduleId === moduleId); 

    if (moduleIndex !== -1) { 
      const picurl = filmSBZPList[moduleIndex].picurl; 
      const removeIndex = e.detail.index; 
      console.log('removeIndex:', removeIndex); 

      if (removeIndex !== undefined) { 
        picurl.splice(removeIndex, 1); 
      } 

      filmSBZPList[moduleIndex].picurl = picurl; 
      this.setData({ filmSBZPList }); 
    } else { 
      console.error('Module not found'); 
    } 
  }, 
  handleClick(e) {
    console.log(e.detail.file);
  },

  handleDrop(e) {
    const { files } = e.detail;
    const moduleId = e.currentTarget.dataset.id;
    const { filmSBZPList } = this.data;

    const moduleIndex = filmSBZPList.findIndex(item => item.moduleId === moduleId); 

    if (moduleIndex !== -1) { 
      const updatedModule = filmSBZPList[moduleIndex];
      updatedModule.picurl = files.map(file => ({ url: file.url }));
      filmSBZPList.splice(moduleIndex, 1, updatedModule);
      this.setData({ filmSBZPList });
    } else {
      console.error('Module not found');
    }
  },
  
    onPickerChange(e) {
    const { value } = e.detail;
    const index = this.data.cityIndex;
    const updatedFilmSBZPList = [...this.data.filmSBZPList];
    updatedFilmSBZPList[index].cityText = value.join(' ');
    this.setData({
      cityVisible: false,
      filmSBZPList: updatedFilmSBZPList,
    });
  },

  onCityPicker(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      cityVisible: true,
      cityIndex: index,
    });
  },

  onPickerCancel(e) {
    const { key } = e.currentTarget.dataset;
    console.log(e, '取消');
    console.log('picker1 cancel:');
    this.setData({
      [`${key}Visible`]: false,
    });
  },
 
  // 数字输入
onPriceInput(e) {
  const { index } = e.currentTarget.dataset; // 获取当前输入框的索引
  const isNumber = /^\d+(\.\d+)?$/.test(e.detail.value);
  const updatedFilmSBZPList = [...this.data.filmSBZPList];
  updatedFilmSBZPList[index].priceError = !isNumber; // 更新当前输入框的错误状态
  this.setData({
    filmSBZPList: updatedFilmSBZPList,
  });
},

  handleUpload() {
    let that = this;
    wx.chooseImage({
      success: chooseResult => {
        wx.showLoading({ title: '上传中' });
  
        wx.cloud.uploadFile({
          cloudPath: 'cars/logo/' + (new Date()).valueOf() + '.png',
          filePath: chooseResult.tempFilePaths[0],
          success: res => {
            wx.hideLoading();
            wx.showToast({ title: '上传图片成功' });
  
            if (res.fileID) {
              if (that.data.oldImgUrl) {
                wx.cloud.deleteFile({
                  fileList: [that.data.oldImgUrl],
                  success: deleteRes => {
                    console.log('旧图片删除成功', deleteRes);
                  },
                  fail: err => {
                    console.error('旧图片删除失败', err);
                  }
                });
              }
  
              that.setData({
                imgUrl: res.fileID,
                oldImgUrl: ''  // 清空旧图片路径
              });
            }
          },
          fail: err => {
            wx.hideLoading();
            wx.showToast({ title: '上传失败，请重试', icon: 'none' });
            console.error('上传失败', err);
          }
        });
      },
      fail: err => {
        wx.showToast({ title: '选择图片失败，请重试', icon: 'none' });
        console.error('选择图片失败', err);
      }
    });
  },

  cancelEdit() {
    this.setData({
      isEditing: false,
      editId: null,
      
    });
  },
  publishRent() {
    let that = this;
  
    if (!that.data.cname || !that.data.business || !that.data.contact) {
      wx.showToast({ title: '请填写完整信息', icon: 'none' });
      return;
    }
  
    const { longitude, latitude } = that.data; // Access longitude and latitude from data
  
    const filmSBZPList = that.data.filmSBZPList.map(item => ({
      ...item,
      priceError: false
    }));
  
    let hasError = false;
    filmSBZPList.forEach(item => {
      if (isNaN(item.price) || item.price <= 0) {
        item.priceError = true;
        hasError = true;
      }
    });
  
    if (hasError) {
      that.setData({ filmSBZPList });
      wx.showToast({ title: '请检查输入的价格', icon: 'none' });
      return;
    }
  
    wx.showLoading({ title: '正在提交...' });
  
    const uploadPromises = filmSBZPList.map((item, index) => {
      if (item.picurl && item.picurl.length > 0 && item.picurl != that.data.oldpicurl) {
        const uploadTasks = item.picurl.map(pic => {
          return new Promise((resolve, reject) => {
            if (pic.url.startsWith('cloud://')) {
              resolve(pic.url);
            } else {
              wx.cloud.uploadFile({
                cloudPath: 'cars/cpicture/' + (new Date()).valueOf() + '.png',
                filePath: pic.url,
                success: res => {
                  if (res.fileID) {
                    resolve(res.fileID);
                  } else {
                    reject('上传失败');
                  }
                },
                fail: err => {
                  reject(err);
                }
              });
            }
          });
        });
  
        return Promise.all(uploadTasks)
          .then(urls => {
            filmSBZPList[index].picurl = urls.map(url => ({ url }));
          })
          .catch(err => {
            wx.showToast({ title: '图片上传失败，请重试', icon: 'none' });
            console.error('图片上传失败', err);
          });
      }
      return Promise.resolve();
    });
  
    Promise.all(uploadPromises)
      .then(() => {
        const db = wx.cloud.database();
        const data = {
          cname: that.data.cname,
          business: that.data.business,
          contact: that.data.contact,
          logo_url: that.data.imgUrl,
          location: that.data.location,
          address: that.data.address,
          locationName: that.data.locationName,
          cars: filmSBZPList,
          location2: [longitude, latitude]
        };
  
        db.collection('cars').doc(that.data.editId).update({
          data,
          success: () => {
            wx.hideLoading();
            wx.showToast({ title: '修改成功', icon: 'success' });
            that.setData({ isEditing: false });
            that.getEquipmentData();
          },
          fail: err => {
            wx.hideLoading();
            wx.showToast({ title: '修改失败，请重试', icon: 'none' });
            console.error('数据库更新失败', err);
          }
        });
      })
      .catch(err => {
        wx.hideLoading();
        wx.showToast({ title: '图片上传失败，请重试', icon: 'none' });
        console.error('图片上传失败', err);
      });
  }
  
  
 
});